package gologv0

import (
	"sync"
)

type MultiFile struct {
	lk     sync.RWMutex
	lstMap map[string]*SingleCacheFileWriter
}

func NewMultiFile() *MultiFile {
	rval := &MultiFile{
		lstMap: make(map[string]*SingleCacheFileWriter),
	}
	return rval
}

var (
	DefaultMultiFile = NewMultiFile()
)

func (this *MultiFile) CheckGet(filename string) *SingleCacheFileWriter {
	this.lk.RLock()
	rval := this.lstMap[filename]
	this.lk.RUnlock()
	if rval != nil {
		return rval
	}
	this.lk.Lock()
	defer this.lk.Unlock()
	rval = this.lstMap[filename]
	if rval == nil {
		rval = NewSingleCacheFileWriter(filename)
		this.lstMap[filename] = rval
	}
	return rval
}

func (this *MultiFile) Close() {
	this.lk.Lock()
	defer this.lk.Unlock()
	for k, itm := range this.lstMap {
		itm.Close()
		delete(this.lstMap, k)
	}
}
